package org.dromara.system.utils;

import org.dromara.common.core.utils.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DianWangUtil {

    public static String handHtmlItemNo(String item_no,String context){
        if(StringUtils.isEmpty(item_no) && StringUtils.isNotEmpty(context)){
            Document doc = Jsoup.parse(context);
            String textOnly = doc.text();// 获取纯文本内容
            return handItemNo(item_no,textOnly);
        }
        return item_no;
    }

    public static String handItemNo(String item_no,String context){
        if(StringUtils.isEmpty(item_no) && StringUtils.isNotEmpty(context)){
            context = context.replaceAll(" ","");
            String regex = "编号：([^\\n^\\s^\\u4e00-\\u9fff]+)";
            String itemNo = getItemNo(regex,context);
            if(StringUtils.isEmpty(itemNo)){
                itemNo = getItemNo("编号:([^\\n^\\s^\\u4e00-\\u9fff]+)",context);
            }
            if(StringUtils.isEmpty(itemNo)){
                itemNo = getItemNo("（([^\\n^\\s^\\u4e00-\\u9fff]+)）",context);
            }
            return itemNo;
        }
        return item_no;
    }

    /**
     * 正则表达式获取项目编号
     * @param regex
     * @param context
     * @return
     */
    private static String getItemNo(String regex,String context){
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(context);
        if (matcher.find()) {
            String captured = matcher.group(1);
            if(captured.length() > 200) {
                captured = captured.substring(0,200);
            }
            if(captured.indexOf(")") > 0 && captured.indexOf("(") < 0){
                captured = captured.substring(0,captured.indexOf(")"));
            }
            if(captured.indexOf("（") > 0 || captured.indexOf("(") > 0){
                return captured.replaceAll("\\s*|\r|\n|\t","");
            }else{
                return captured.replaceAll("\\s*|\r|\n|\t","").replaceAll("）","").replaceAll("\\)","");
            }
        }
        return null;
    }

}
